import express, { Router } from 'express';
import { PrismaClient } from '@prisma/client';
import response from '../utils/response';
import { authenticateToken } from '../middleware/auth';
import upload from '../middleware/upload';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 获取当前激活的首页配置（客户端用）
router.get('/active', async (req, res) => {
  try {
    const homepage = await prisma.homepage.findFirst({
      where: { isActive: true },
      include: {
        sections: {
          where: { isVisible: true },
          orderBy: { sortOrder: 'asc' },
          include: {
            items: {
              where: { isVisible: true },
              orderBy: { sortOrder: 'asc' }
            }
          }
        }
      }
    });

    if (!homepage) {
      return response.error(res, '未找到激活的首页配置', 404);
    }

    return response.success(res, homepage, '获取首页配置成功');
  } catch (error) {
    console.error('获取首页配置失败:', error);
    return response.error(res, '获取首页配置失败');
  }
});

// 获取所有首页配置（管理端用）
router.get('/', authenticateToken, async (req, res) => {
  try {
    const homepages = await prisma.homepage.findMany({
      include: {
        sections: {
          orderBy: { sortOrder: 'asc' },
          include: {
            items: {
              orderBy: { sortOrder: 'asc' }
            }
          }
        }
      },
      orderBy: { createdAt: 'desc' }
    });

    return response.success(res, homepages, '获取所有首页配置成功');
  } catch (error) {
    console.error('获取首页配置失败:', error);
    return response.error(res, '获取首页配置失败');
  }
});

// 创建新的首页配置
router.post('/', authenticateToken, async (req, res) => {
  try {
    // 先将其他配置设为非激活
    await prisma.homepage.updateMany({
      where: { isActive: true },
      data: { isActive: false }
    });

    const homepage = await prisma.homepage.create({
      data: {
        isActive: true
      }
    });

    return response.success(res, homepage, '创建首页配置成功');
  } catch (error) {
    console.error('创建首页配置失败:', error);
    return response.error(res, '创建首页配置失败');
  }
});

// 更新首页配置
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { isActive } = req.body;

    // 如果要设为激活，先将其他配置设为非激活
    if (isActive) {
      await prisma.homepage.updateMany({
        where: { 
          isActive: true,
          NOT: { id: parseInt(id) }
        },
        data: { isActive: false }
      });
    }

    const homepage = await prisma.homepage.update({
      where: { id: parseInt(id) },
      data: { isActive },
      include: {
        sections: {
          include: {
            items: true
          }
        }
      }
    });

    return response.success(res, homepage, '更新首页配置成功');
  } catch (error) {
    console.error('更新首页配置失败:', error);
    return response.error(res, '更新首页配置失败');
  }
});

// 删除首页配置
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;

    await prisma.homepage.delete({
      where: { id: parseInt(id) }
    });

    return response.success(res, null, '删除首页配置成功');
  } catch (error) {
    console.error('删除首页配置失败:', error);
    return response.error(res, '删除首页配置失败');
  }
});

// 创建首页区块
router.post('/section', authenticateToken, async (req, res) => {
  try {
    const section = await prisma.homepageSection.create({
      data: req.body,
      include: {
        items: true
      }
    });

    return response.success(res, section, '创建首页区块成功');
  } catch (error) {
    console.error('创建首页区块失败:', error);
    return response.error(res, '创建首页区块失败');
  }
});

// 更新首页区块
router.put('/section/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;

    const section = await prisma.homepageSection.update({
      where: { id: parseInt(id) },
      data: req.body,
      include: {
        items: true
      }
    });

    return response.success(res, section, '更新首页区块成功');
  } catch (error) {
    console.error('更新首页区块失败:', error);
    return response.error(res, '更新首页区块失败');
  }
});

// 删除首页区块
router.delete('/section/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;

    await prisma.homepageSection.delete({
      where: { id: parseInt(id) }
    });

    return response.success(res, null, '删除首页区块成功');
  } catch (error) {
    console.error('删除首页区块失败:', error);
    return response.error(res, '删除首页区块失败');
  }
});

// 创建区块项目
router.post('/section/item', authenticateToken, async (req, res) => {
  try {
    const item = await prisma.homepageSectionItem.create({
      data: req.body
    });

    return response.success(res, item, '创建区块项目成功');
  } catch (error) {
    console.error('创建区块项目失败:', error);
    return response.error(res, '创建区块项目失败');
  }
});

// 更新区块项目
router.put('/section/item/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;

    const item = await prisma.homepageSectionItem.update({
      where: { id: parseInt(id) },
      data: req.body
    });

    return response.success(res, item, '更新区块项目成功');
  } catch (error) {
    console.error('更新区块项目失败:', error);
    return response.error(res, '更新区块项目失败');
  }
});

// 删除区块项目
router.delete('/section/item/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;

    await prisma.homepageSectionItem.delete({
      where: { id: parseInt(id) }
    });

    return response.success(res, null, '删除区块项目成功');
  } catch (error) {
    console.error('删除区块项目失败:', error);
    return response.error(res, '删除区块项目失败');
  }
});

// 批量更新区块项目
router.put('/section/:sectionId/items', authenticateToken, async (req, res) => {
  try {
    const { sectionId } = req.params;
    const { items } = req.body;

    // 先删除该区块下的所有项目
    await prisma.homepageSectionItem.deleteMany({
      where: { sectionId: parseInt(sectionId) }
    });

    // 创建新的项目
    if (items && items.length > 0) {
      await prisma.homepageSectionItem.createMany({
        data: items.map((item: any) => ({
          ...item,
          sectionId: parseInt(sectionId)
        }))
      });
    }

    // 获取更新后的区块
    const section = await prisma.homepageSection.findUnique({
      where: { id: parseInt(sectionId) },
      include: {
        items: {
          orderBy: { sortOrder: 'asc' }
        }
      }
    });

    return response.success(res, section, '批量更新区块项目成功');
  } catch (error) {
    console.error('批量更新区块项目失败:', error);
    return response.error(res, '批量更新区块项目失败');
  }
});

// 上传图片
router.post('/upload/image', authenticateToken, upload.single('file'), async (req: any, res) => {
  try {
    if (!req.file) {
      return response.error(res, '请选择要上传的文件');
    }

    // 构建可访问的URL路径
    const baseUrl = process.env.SERVER_BASE_URL || `http://localhost:${process.env.PORT || 3000}`;
    const fileUrl = `${baseUrl}/uploads/${req.file.filename}`;

    // 记录文件上传信息
    const fileRecord = await prisma.fileUpload.create({
      data: {
        filename: req.file.filename,
        originalName: req.file.originalname,
        mimetype: req.file.mimetype,
        size: req.file.size,
        ossUrl: fileUrl,
        category: 'homepage',
        uploadedBy: req.user?.username
      }
    });

    return response.success(res, {
      url: fileRecord.ossUrl,
      fileId: fileRecord.id
    }, '上传图片成功');
  } catch (error) {
    console.error('上传图片失败:', error);
    return response.error(res, '上传图片失败');
  }
});

// 复制首页配置
router.post('/:id/duplicate', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;

    // 获取原配置
    const original = await prisma.homepage.findUnique({
      where: { id: parseInt(id) },
      include: {
        sections: {
          include: {
            items: true
          }
        }
      }
    });

    if (!original) {
      return response.error(res, '原配置不存在', 404);
    }

    // 创建新配置
    const newHomepage = await prisma.homepage.create({
      data: {
        isActive: false,
        sections: {
          create: original.sections.map(section => ({
            sectionKey: section.sectionKey,
            sectionType: section.sectionType,
            titleEn: section.titleEn,
            titleEs: section.titleEs,
            titleJa: section.titleJa,
            subtitleEn: section.subtitleEn,
            subtitleEs: section.subtitleEs,
            subtitleJa: section.subtitleJa,
            contentEn: section.contentEn,
            contentEs: section.contentEs,
            contentJa: section.contentJa,
            backgroundImage: section.backgroundImage,
            sortOrder: section.sortOrder,
            isVisible: section.isVisible,
            items: {
              create: section.items.map(item => ({
                titleEn: item.titleEn,
                titleEs: item.titleEs,
                titleJa: item.titleJa,
                descriptionEn: item.descriptionEn,
                descriptionEs: item.descriptionEs,
                descriptionJa: item.descriptionJa,
                image: item.image,
                icon: item.icon,
                link: item.link,
                buttonTextEn: item.buttonTextEn,
                buttonTextEs: item.buttonTextEs,
                buttonTextJa: item.buttonTextJa,
                sortOrder: item.sortOrder,
                isVisible: item.isVisible
              }))
            }
          }))
        }
      },
      include: {
        sections: {
          include: {
            items: true
          }
        }
      }
    });

    return response.success(res, newHomepage, '复制首页配置成功');
  } catch (error) {
    console.error('复制首页配置失败:', error);
    return response.error(res, '复制首页配置失败');
  }
});

export default router;